package com.ruoyi.socket.probuffer.client;


import com.google.protobuf.ByteString;
import com.ruoyi.socket.probuffer.DataInfo;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ProtoClientHandler extends SimpleChannelInboundHandler<DataInfo.DeviceData> {



    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DataInfo.DeviceData msg) throws Exception {
        String s = msg.getContent().toStringUtf8();
        System.out.println("从socket读取内容 "+s);
        //System.out.println("client received: " +msg);

        DataInfo.DeviceData data = DataInfo.DeviceData.newBuilder()
                .setDeviceID("1")
                .setDevicetype("A001")
                .setDeviceName("瑞博呼吸机")
                .setControlMsg("发送启动指令")
                .setGateInfo("网关info网络环境不错")
                .setGatewayID("网关A001")
                .setContent(ByteString.copyFromUtf8("channelRead0 这是设备数据dataInfo{'a':'b','c':12,'d':true}"))
                .build();
        ctx.channel().writeAndFlush(data);


        //读取之后，关闭socket链接
        ctx.channel().close().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()){
                    System.out.println("client 关闭连接...");
                }
            }
        });
    }






    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

       DataInfo.DeviceData data = DataInfo.DeviceData.newBuilder()
                .setDeviceID("1")
                .setDevicetype("A001")
                .setDeviceName("瑞博呼吸机")
                .setControlMsg("发送启动指令")
                .setGateInfo("网关info网络环境不错")
                .setGatewayID("网关A001")
                .setContent(ByteString.copyFromUtf8("channelActive 这是设备数据dataInfo{'a':'b','c':12,'d':true}"))


        .build();
        ctx.channel().writeAndFlush(data);

    }
}